package com.aplikata.evok.ui;

import java.io.File;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.RequestScoped;
import javax.faces.event.ActionEvent;

import org.apache.myfaces.custom.fileupload.UploadedFile;
import org.primefaces.event.NodeSelectEvent;
import org.primefaces.event.RowEditEvent;
import org.primefaces.event.SelectEvent;
import org.primefaces.model.TreeNode;

import com.aplikata.constants.ConstantsMsg;
import com.aplikata.evok.bo.Qt;
import com.aplikata.evok.bo.QtCategory;
import com.aplikata.evok.bo.Qtnaire;
import com.aplikata.evok.constants.EvokConstants;
import com.aplikata.evok.datamodel.QtCategoryDataModel;
import com.aplikata.evok.datamodel.QtDataModel;
import com.aplikata.evok.service.EvokQtnaireService;
import com.aplikata.ui.UIBean;
import com.aplikata.util.FacesUtil;
import com.aplikata.util.FileUtil;
import com.aplikata.util.StringUtil;

@ManagedBean(name = "evokQtnaireBean")
@RequestScoped
public class EvokQtnaireBean extends UIBean {
	private static final long serialVersionUID = 1L;

	private Qtnaire qtnaire;
	private Qtnaire parent;

	@ManagedProperty(value = "#{evokQtnaireService}")
	private EvokQtnaireService evokQtnaireService;
	private List<Qtnaire> qtnaireParenList;

	private TreeNode rootQtnaire;
	private TreeNode selectedQtnaire;
	
	private QtCategory qtCategory;
	private List<QtCategory> qtCategoryList;
	private QtCategoryDataModel categoryModel;
	
	private Qt qt;
	private List<Qt> qtList;
	private QtDataModel qtModel;
	
	private UploadedFile upFile;

	@PostConstruct
	public void init() {
		qtnaire = new Qtnaire();
		parent = new Qtnaire();
	}

	public void add() {
		if (qtnaire == null || FacesUtil.isKeyNull(qtnaire.getId())) {
			qtnaire = new Qtnaire();
			parent = new Qtnaire();
		} else {
			parent = qtnaire;
			qtnaire = new Qtnaire(parent);
		}
	}

	public void submit(ActionEvent event) {
		if (qtnaire == null) {
			return;
		}
		try {
			if(StringUtil.isStrEmpty(qtnaire.getName())){
				FacesUtil.addErrorMessage(ConstantsMsg.MSG_REQUIRE, new Object[]{FacesUtil.getMessage("default_name")});
				return;
			}
				
			if (FacesUtil.isKeyNull(qtnaire.getId()))
				qtnaire.setId(null);

			if (FacesUtil.isKeyNull(parent.getId()))
				parent = null;

			qtnaire.setParent(parent);
			qtnaire = (Qtnaire) evokQtnaireService.merge(qtnaire);
			FacesUtil.addInfoMessage("info_content_add_success", new Object[] { qtnaire.getName() });
			qtnaire = new Qtnaire();
			parent = new Qtnaire();
			rootQtnaire = evokQtnaireService.getRootQtnaire(null);
		} catch (Exception e) {
			FacesUtil.addActionListenerException(e, log);
		}
	}
	
	public String submitImage() throws Exception {
		if (upFile != null && qt != null && !FacesUtil.isKeyNull(qt.getId())) {
			String attname = upFile.getName();
			attname = attname.substring(attname.lastIndexOf("\\") + 1, attname.length());
			attname = "qt" + qt.getQtCategory().getId().toString() + "-" + qt.getId().toString()
					+ attname;
			String filename = FacesUtil.getServletContext().getRealPath("/" + EvokConstants.IMAGES_FOLDER  + "\\qt\\" + attname);
			
			FileUtil.writeToFile(upFile.getInputStream(), filename);
			if(qt.getImgUrl() != null){
				String imgFileName = qt.getImgUrl().substring(qt.getImgUrl().lastIndexOf("/") + 1, qt.getImgUrl().length());
				filename = FacesUtil.getServletContext().getRealPath("/" + EvokConstants.IMAGES_FOLDER  + "\\qt\\" + imgFileName);
				File f= new File(filename);
				if(f.exists() && f.isFile())
					f.delete();
			}
			/*qt.setImgUrl(FacesUtil.getServletContext().getContextPath() + "/" + EvokConstants.IMAGES_FOLDER + "/qt/"
					+ attname);*/
			qt.setImgUrl("/" + EvokConstants.IMAGES_FOLDER + "/qt/"
			+ attname);
			evokQtnaireService.merge(qt);
			FacesUtil.addInfoMessage("info_content_add_success", new Object[] { qt.getName() });
			qtList = null;
		}
		return "/pages/aplikata/evok/qtnaire_evok";
	}

	public void delete() {
		try {
			if (qtnaire == null) {
				return;
			}

			evokQtnaireService.deleteQtnaire(qtnaire);
			FacesUtil.addInfoMessage("info_content_delete_success", new Object[] { qtnaire.getName() });
			qtnaire = new Qtnaire();
			rootQtnaire = evokQtnaireService.getRootQtnaire(null);
		} catch (Exception e) {
			FacesUtil.addActionListenerException(e, log);
		}
	}

	public void onNodeSelect(NodeSelectEvent event) {
		selectedQtnaire = event.getTreeNode();
		qtnaire = (Qtnaire) selectedQtnaire.getData();
		
		qtCategoryList = null;
		qtCategory = new QtCategory(qtnaire);
		qtList = null;
		
		parent = qtnaire.getParent();

		if (parent == null) {
			parent = new Qtnaire();
		}
	}
	
	public void categoryEdit(RowEditEvent e) {
		int index = qtCategoryList.indexOf(e.getObject());
		qtCategory = (QtCategory) e.getObject();
		
		if(StringUtil.isStrEmpty(qtCategory.getName())){
			FacesUtil.addErrorMessage(ConstantsMsg.MSG_REQUIRE, new Object[]{FacesUtil.getMessage("default_name")});
			return;
		}
			
		QtCategory temp = (QtCategory) evokQtnaireService.merge(qtCategory);
		qtCategoryList.remove(index);
		qtCategoryList.add(index, temp);
		
		FacesUtil.addInfoMessage("info_content_edit_success", new Object[] { qtCategory.getName() });
	}
	
	public void qtEdit(RowEditEvent e) {
		int index = qtList.indexOf(e.getObject());
		qt = (Qt) e.getObject();
		
		if(StringUtil.isStrEmpty(qt.getName())){
			FacesUtil.addErrorMessage(ConstantsMsg.MSG_REQUIRE, new Object[]{FacesUtil.getMessage("default_name")});
			return;
		}
			
		Qt temp = (Qt) evokQtnaireService.merge(qt);
		qtList.remove(index);
		qtList.add(index, temp);
		
		FacesUtil.addInfoMessage("info_content_edit_success", new Object[] { qt.getName() });
	}
	
	public void categorySelect(SelectEvent event) {
		qtCategory = (QtCategory) event.getObject();
		if (qtCategory == null || FacesUtil.isKeyNull(qtCategory.getId()))
			return;
		qtList = null;
	}
	
	public void qtSelect(SelectEvent event) {
		qt= (Qt) event.getObject();
	}
	
	public void deleteCategoryAction(ActionEvent event) {
		try {
			if (qtCategory == null || FacesUtil.isKeyNull(qtCategory.getId())) {
				if (qtCategoryList.contains(qtCategory))
					qtCategoryList.remove(qtCategory);
				return;
			}
			evokQtnaireService.deleteQtCategory(qtCategory);
			FacesUtil.addInfoMessage("info_content_delete_success", new Object[] { qtCategory.getName() });
			qtCategoryList.remove(qtCategory);
		} catch (Exception e) {
			FacesUtil.addActionException(e, log);
		}
	}
	
	public void deleteQtAction(ActionEvent event) {
		try {
			if (qt == null || FacesUtil.isKeyNull(qt.getId())) {
				if (qtList.contains(qt))
					qtList.remove(qt);
				return;
			}
			evokQtnaireService.deleteByKey(Qt.class, qt.getId());
			FacesUtil.addInfoMessage("info_content_delete_success", new Object[] { qt.getName() });
			qtList.remove(qt);
		} catch (Exception e) {
			FacesUtil.addActionException(e, log);
		}
	}
	
	public void addCategoryAction(ActionEvent event) {
		if (qtnaire == null || FacesUtil.isKeyNull(qtnaire.getId()))
			return;
		qtCategory = new QtCategory(qtnaire);
		qtCategoryList.add(0, qtCategory);
	}
	
	public void addQtAction(ActionEvent event) {
		if (qtCategory == null || FacesUtil.isKeyNull(qtCategory.getId()))
			return;
		qt = new Qt(qtCategory);
		qtList.add(0, qt);
	}


	public TreeNode getRootQtnaire() {
		if (rootQtnaire == null) {
			rootQtnaire = evokQtnaireService.getRootQtnaire(null);
		}
		return rootQtnaire;
	}

	public void setRootQtnaire(TreeNode rootQtnaire) {
		this.rootQtnaire = rootQtnaire;
	}

	public TreeNode getSelectedQtnaire() {
		return selectedQtnaire;
	}

	public void setSelectedQtnaire(TreeNode selectedQtnaire) {
		this.selectedQtnaire = selectedQtnaire;
	}

	public Qtnaire getQtnaire() {
		return qtnaire;
	}

	public void setQtnaire(Qtnaire qtnaire) {
		this.qtnaire = qtnaire;
	}

	public Qtnaire getParent() {
		return parent;
	}

	public void setParent(Qtnaire parent) {
		this.parent = parent;
	}

	public EvokQtnaireService getEvokQtnaireService() {
		return evokQtnaireService;
	}

	public void setEvokQtnaireService(EvokQtnaireService evokQtnaireService) {
		this.evokQtnaireService = evokQtnaireService;
	}

	public List<Qtnaire> getQtnaireParenList() {
		return qtnaireParenList;
	}

	public void setQtnaireParenList(List<Qtnaire> qtnaireParenList) {
		this.qtnaireParenList = qtnaireParenList;
	}

	public QtCategory getQtCategory() {
		return qtCategory;
	}

	public void setQtCategory(QtCategory qtCategory) {
		this.qtCategory = qtCategory;
	}

	@SuppressWarnings("unchecked")
	public List<QtCategory> getQtCategoryList() {
		if (qtCategoryList == null && qtnaire != null && !FacesUtil.isKeyNull(qtnaire.getId())) {
			qtCategoryList = (List<QtCategory>) evokQtnaireService.findByNamedQuery(QtCategory.QY_FIND_BY_QTNAIRE,
					new Object[] { qtnaire.getId() });
		}
		return qtCategoryList;
	}

	public void setQtCategoryList(List<QtCategory> qtCategoryList) {
		this.qtCategoryList = qtCategoryList;
	}

	public QtCategoryDataModel getCategoryModel() {
		if (categoryModel == null) {
			categoryModel = new QtCategoryDataModel(evokQtnaireService, getQtCategoryList());
		}
		return categoryModel;
	}

	public void setCategoryModel(QtCategoryDataModel categoryModel) {
		this.categoryModel = categoryModel;
	}

	public Qt getQt() {
		return qt;
	}

	public void setQt(Qt qt) {
		this.qt = qt;
	}

	@SuppressWarnings("unchecked")
	public List<Qt> getQtList() {
		if (qtList == null && qtCategory != null && !FacesUtil.isKeyNull(qtCategory.getId())) {
			qtList = (List<Qt>) evokQtnaireService.findByNamedQuery(Qt.QY_FIND_BY_CATEGORY,
					new Object[] { qtCategory.getId() });
		}
		return qtList;
	}

	public void setQtList(List<Qt> qtList) {
		this.qtList = qtList;
	}

	public QtDataModel getQtModel() {
		if (qtModel == null) {
			qtModel = new QtDataModel(evokQtnaireService, getQtList());
		}
		return qtModel;
	}

	public void setQtModel(QtDataModel qtModel) {
		this.qtModel = qtModel;
	}

	public UploadedFile getUpFile() {
		return upFile;
	}

	public void setUpFile(UploadedFile upFile) {
		this.upFile = upFile;
	}
}
